import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/team/soccer/zq_team_schedule_logic.dart';
import 'package:sports_new/entity/team/zq_team_schedule_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../../widgets/base/qkd_text.dart';

class ZqTeamScheduleView extends StatefulWidget {
  const ZqTeamScheduleView({super.key, required this.teamId});
  final int teamId;

  @override
  State<ZqTeamScheduleView> createState() => _ZqTeamScheduleViewState();
}

class _ZqTeamScheduleViewState extends State<ZqTeamScheduleView>
    with AutomaticKeepAliveClientMixin {
  late final ZqTeamScheduleLogic logic =
      Get.put(ZqTeamScheduleLogic(), tag: widget.teamId.toString());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<ZqTeamScheduleLogic>(
      initState: (state) async {
        await logic.requestYears(widget.teamId);
        await logic.requestData(widget.teamId);
        Future.delayed(
          const Duration(milliseconds: 500)
        ).then(
          (value) => logic.initObserver()
        );
      },
      tag: widget.teamId.toString(),
      builder: (controller) {
        return LoadingWidget<bool>(
          isLoading: controller.years == null,
          data: controller.years?.length == 0,
          child: () => Container(
            color: Colours.scaffoldBg,
            child: Column(
              children: [
                _pageChoice(),
                Expanded(
                  child: LoadingWidget<bool>(
                    isLoading: controller.matchGroup == null,
                    data: controller.matchGroup?.length == 0,
                    child: () => MediaQuery.removePadding(
                      context: context,
                      removeTop: true,
                      child: controller.years?[controller.yearIndex].count == 0
                        ? const NoDataWidget()
                        : ListView(
                          controller: controller.scrollC,
                          physics: const ClampingScrollPhysics(),
                          children: List.generate(
                            controller.matchGroup?.length ?? 0,
                            (index) => _listItem(index).paddingOnly(
                              bottom: (controller.matchGroup?.length == index + 1)?50:0
                            )
                          )
                      ),
                    ),
                  )
                ),
              ],
            ),
          ),
        );
      }
    );
  }

  Widget _pageChoice() {
    return Container(
      height: 34,
      color: Colours.white,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 12, right: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () async {
              await logic.showDatePicker();
              await logic.requestData(widget.teamId);
              await Future.delayed(const Duration(microseconds: 500)).then(
                (value) => logic.observerController.jumpTo(
                  index: logic.years?[logic.yearIndex].year.toString() == DateTime.now().formatedString('yyyy') ?
                    logic.data?.matchGroup?.indexWhere((element) =>
                      element.title == DateTime.now().formatedString('yyyy-MM')) ?? 0 : (logic.data?.matchGroup?.length ?? 1) - 1
                )
              );
            },
            child: Container(
              height: 24,
              width: 57,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 6, right: 2),
              decoration: BoxDecoration(
                  color: Colours.greyF5F7FA,
                  borderRadius: BorderRadius.circular(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QkdText("${logic.years?[logic.yearIndex].year ?? ''}",
                      needCenter: true, fontSize: 12
                    ),
                    const SizedBox(width: 2),
                    Padding(
                      padding: const EdgeInsets.only(top: 1),
                      child: Image.asset(
                        Utils.getImgPath('down_arrow.png'),
                        width: 8,
                        height: 6,
                      ),
                    )
                  ]),
            ),
          ),
          Container(width: 5),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                    logic.data?.leagueArray?.length ?? 0,
                    (childIndex) => Flexible(
                          flex: 1,
                          child: GestureDetector(
                            onTap: () async {
                              logic.getType(childIndex);
                            },
                            child: Container(
                              height: 24,
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 15),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(30),
                                  color: logic.typeIndex == childIndex
                                      ? Colours.main
                                      : Colours.white),
                              child: QkdText(
                                logic.data?.leagueArray?[childIndex]
                                  .leagueName ?? "",
                                color: logic.typeIndex == childIndex
                                  ? Colours.white
                                  : Colours.grey66,
                                needCenter: true
                              ),
                            ),
                          ),
                        )),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _listItem(itemIndex) {
    return Container(
      margin: const EdgeInsets.only(top: 8, left: 8, right: 8),
      decoration: BoxDecoration(
          color: Colours.white, borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.only(bottom: 8),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: Get.width,
              height: 38,
              alignment: Alignment.center,
              child: QkdText(
                "${(logic.matchGroup?[itemIndex].title ?? "").split('-').join('年')}月",
                fontSize: 13, fontWeight: FontWeight.w500
              )
            ),
            Column(
              children: List.generate(
                  logic.matchGroup?[itemIndex].matchArray?.length ?? 0,
                  (index) => _childItem(
                      logic.matchGroup?[itemIndex].matchArray?[index])),
            )
          ],
        ),
      ),
    );
  }

  Widget _childItem(MatchArray? entity) {
    return GestureDetector(
      onTap: () =>
          Get.toNamed(Routes.zqMatchDetail, arguments: entity?.qxbMatchId),
      child: Stack(
        alignment: Alignment.center,
        children: [
          SizedBox(
            height: 50,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(width: 12),
                SizedBox(
                  width: 72,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QkdText(
                        DateTime.parse(entity?.matchTime ?? '')
                          .formatedString("MM-dd HH:mm") ?? "-",
                        fontSize: 12,fontWeight: FontWeight.w400,
                        color: Colours.grey666666
                      ),
                      QkdText(
                        (entity?.leagueName != null && entity?.leagueName != ''
                                ? "${entity!.leagueName}\u2000"
                                : "") +
                            (entity?.groupCn != null && entity?.groupCn != ''
                                ? entity!.groupCn!
                                : ""),
                        color: Colours.grey99, fontSize: 10
                      )
                    ],
                  ),
                ),
                Container(width: 7),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: QkdText(entity?.homeName ?? "-",
                        fontSize: 13,
                        maxLines: 2,
                        textAlign: TextAlign.end),
                  ),
                ),
                // Padding(
                //   padding: const EdgeInsets.only(left: 6),
                //   child: Container(
                //     alignment: Alignment.centerRight,
                //     width: 21,
                //     height: 21,
                //     decoration: const BoxDecoration(shape: BoxShape.circle),
                //     child: CachedNetworkImage(
                //         placeholder: (context, url) => Styles.placeholderIcon(),
                //         errorWidget: (context, url, error) =>
                //             Image.asset(Utils.getImgPath("zq_placeholder.png")),
                //         imageUrl: entity?.homeLogo ?? ""),
                //   ),
                // ),
                SizedBox(
                  width: 50,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QkdText(logic.formScore(1, entity),
                          fontSize: 15,fontWeight: FontWeight.w500
                      ),
                      logic.formScore(2, entity) == ""
                        ? Container()
                        : QkdText(logic.formScore(2, entity),
                        fontSize: 10, color: Colours.grey66
                      )
                    ],
                  ),
                ),
                // Padding(
                //   padding: const EdgeInsets.only(right: 6),
                //   child: Container(
                //     width: 21,
                //     height: 21,
                //     decoration: const BoxDecoration(shape: BoxShape.circle),
                //     child: CachedNetworkImage(
                //         placeholder: (context, url) => Styles.placeholderIcon(),
                //         errorWidget: (context, url, error) =>
                //             Image.asset(Utils.getImgPath("zq_placeholder.png")),
                //         imageUrl: entity?.guestLogo ?? ''),
                //   ),
                // ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: QkdText(entity?.guestName ?? '-',
                      fontSize: 13,
                      maxLines: 2,
                      textAlign: TextAlign.start
                    ),
                  ),
                ),
                Container(width: 10)
              ],
            ),
          ),
          if (entity?.isWin != null)
            Positioned(
              right: 0,
              // top: 0,
              child: Container(
                height: 14,
                width: 14,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(2),
                      topRight: Radius.circular(2)),
                  color: [
                    Colours.green,
                    Colours.redF13333,
                    Colours.main
                  ][entity!.isWin!]),
                child: QkdText(["负", "胜", "平"][entity.isWin!],
                    fontSize: 10, color: Colors.white
                )
              )
            )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
